//
//  ShellSettingViewController.m
//  ShellWallert
//
//  Created by lvzhao on 2019/9/26.
//  Copyright © 2019年 VV. All rights reserved.
//

#import "ShellSettingViewController.h"
#import "LZBaseTableView.h"
#import "ShellSettingCell.h"
#import "ShellSettingModel.h"
#import "ShellModifyPersonInfoViewController.h"
#import "ShellMineViewModel.h"

@interface ShellSettingViewController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic,strong) LZBaseTableView *tableView;

@property (nonatomic,strong) NSMutableArray *dataArray;

@property (nonatomic,strong) ShellMineViewModel *viewModel;


@end

@implementation ShellSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = LZLocalizedString(@"设置");
    
    [self setupUI];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //刷新数据
    [self createInfoData];
}

- (void)setupUI{
    UIView *headView = [[UIView alloc] init];
    headView.frame = CGRectMake(0, 0, K_SCREENWIDTH, 10);
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    self.tableView.tableHeaderView = headView;
    
    ///创建数据
    [self createInfoData];
    
    //更新数据//昵称
    @weakify(self);
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:k_APPUserInfoWillChangeNotificationName object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        [self createInfoData];
    }];
    
    
}

//创建数据
- (void)createInfoData{
    
    [self.dataArray removeAllObjects];
    ShellUserDetailModel *infoModel = [LZToolCache getUserInfo];
    NSArray *titles = @[@"头像",@"昵称",@"邮箱"];
    NSArray *details = @[@"",infoModel.name?:@"",infoModel.email?:@""];
    
    ShellUserDetailModel *detailModel = [LZToolCache getUserInfo];
    
    for (int i = 0; i < titles.count; i++){
        ShellSettingModel *mineModel = [[ShellSettingModel alloc] init];
        mineModel.title = LZLocalizedString(titles[i]);
        mineModel.detail = details[i];

        if(i == 0){
            mineModel.imageUrl = detailModel.portrait;
        } 
        [self.dataArray addObject:mineModel];
    }
    [self.tableView reloadData];
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ShellSettingCell *mineCell = [tableView dequeueReusableCellWithIdentifier:@"ShellSettingCell"];
    mineCell.indexPath = indexPath;
    mineCell.modelObject = self.dataArray[indexPath.row];
    return mineCell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.row) {
        case 0:
            return 88;
            break;
            
        default:
            return 58;
            break;
    }
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.row) {
        case 0:
        {
            [self changeHeadImageView];
        }
            break;
        case 1:
        {
            ShellModifyPersonInfoViewController *modifyVC = [[ShellModifyPersonInfoViewController alloc] init];
            ShellUserDetailModel *infoModel = [LZToolCache getUserInfo];
            modifyVC.nickName = infoModel.name;
            modifyVC.title = LZLocalizedString(@"昵称");
            [LZTool.currentViewController.navigationController pushViewController:modifyVC animated:YES];
            
        }
            break;
        case 2:
        {

        }
            break;
            
        default:
            break;
    }
    
    
    
}


//修改头像
- (void)changeHeadImageView{
    
    
    NSArray *subtitles = @[LZLocalizedString(@"拍照"),
                           LZLocalizedString(@"从相册中选择"),
                           LZLocalizedString(@"取消")];
    @weakify(self);
    [LZToolView showAlertType:LZAlertViewTypeActionSheet withTitle:nil
                      message:nil
                       cancel:nil
                         sure:nil
                   objectDict:@{@"subtitles":subtitles}
                  cancelBlock:^(id  _Nonnull object){}
                    sureBlock:^(id  _Nonnull object) {
                        NSInteger index = [object integerValue];
                        @strongify(self);
                        [self selectImage:index];
                    }];
    
}


#pragma mark - custool
//跳转相机 相册
- (void)selectImage:(NSInteger)index{
    
    //照片的选取样式还有以下两种
    //UIImagePickerControllerSourceTypePhotoLibrary,直接全部呈现系统相册
    //UIImagePickerControllerSourceTypeCamera//调取摄像头
    //选择完成图片或者点击取消按钮都是通过代理来操作我们所需要的逻辑过程
    dispatch_async(dispatch_get_main_queue(), ^{
        UIImagePickerController *pickerController = [[UIImagePickerController alloc]init];
        pickerController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:COLOR_TEXT,NSFontAttributeName:[UIFont systemFontOfSize:17]};
        UIBarButtonItem *back = [[UIBarButtonItem alloc] init];
        pickerController.navigationBar.barTintColor = [UIColor whiteColor];
        back.title = @"";
        pickerController.navigationItem.backBarButtonItem = back;
        //设置选取的照片是否可编辑
        pickerController.allowsEditing = YES;
        pickerController.delegate = self;
        //设置相册呈现的样式
        pickerController.sourceType = (index == 0) ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypePhotoLibrary;
        //图片分组列表样式
        // 校验相机权限
        [LZ_BoolJudge lz_accessPrivacyPermissionWithType:(index == 0) ? LZ_PermissionTypeCamera :LZ_PermissionTypeAlbum completion:^(BOOL response) {
            if (response) {
                //使用模态呈现相册
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    UIViewController *topVC =  LZTool.currentViewController;
                    pickerController.modalPresentationStyle = UIModalPresentationFullScreen;
                    [topVC presentViewController:pickerController animated:YES completion:^{}];
                });
            }
        }];
        
    });
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage* image = info[UIImagePickerControllerEditedImage];
    if(!image) {
        image = info[UIImagePickerControllerOriginalImage];
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
    //更新信息
    [self.viewModel updateUserHeadImg:image];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - get && set
- (LZBaseTableView *)tableView{
    if(!_tableView){
        _tableView = [[LZBaseTableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.scrollEnabled = NO;
        _tableView.backgroundColor = COLOR_BACKGROUND;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ShellSettingCell class] forCellReuseIdentifier:@"ShellSettingCell"];
    }
    return _tableView;
}

- (NSMutableArray *)dataArray{
    if(!_dataArray){
        _dataArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataArray;
}

- (ShellMineViewModel *)viewModel{
    if(!_viewModel){
        _viewModel = [[ShellMineViewModel alloc] init];
    }
    return _viewModel;
}
@end
